

#import "PersonalContactXMLReader.h"
#import "IDominoAppDelegate.h"
static NSUInteger parsedPersonEntriesCounter;

@implementation PersonalContactXMLReader

@synthesize currentPersonObject = _currentPersonObject;
@synthesize currentColumnNumber=_currentColumnNumber;
@synthesize allPersonNumber = _allPersonNumber;
@synthesize contentOfCurrentPersonProperty = _contentOfCurrentPersonProperty;
@synthesize contacts = _contacts;

#define MAX_PERSONS 1000

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    parsedPersonEntriesCounter = 0;
}

- (NSArray*)parseXMLFileFromData:(NSData *)data parseError:(NSError **)error
{	
	self.contacts=[[NSMutableArray alloc] init];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [parser setDelegate:self];
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    
    [parser parse];
    
    NSError *parseError = [parser parserError];
    if (parseError && error) {
        *error = parseError;
    }
    
    [parser release];
	return self.contacts;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if (qName) {
        elementName = qName;
    }  
    if ([elementName isEqualToString:@"viewentries"]) {
		NSNumber *topLevelEntries = [attributeDict valueForKey:@"toplevelentries"];
		self.allPersonNumber=topLevelEntries;
		return;
	}
	if ([elementName isEqualToString:@"viewentry"]) {	
		if([attributeDict valueForKey:@"unid"]==nil){
			self.currentPersonObject=nil;
			return;
		}
        parsedPersonEntriesCounter++;
		if (parsedPersonEntriesCounter > MAX_PERSONS) {
			[parser abortParsing];
		}		
        // create an instance of it.
        self.currentPersonObject = [[Person alloc] init];
		[self.currentPersonObject setUNID:[attributeDict valueForKey:@"unid"]];
    }
        
    if ([elementName isEqualToString:@"entrydata"]) {
        self.currentColumnNumber = [attributeDict valueForKey:@"columnnumber"];
		
    } else if ([elementName isEqualToString:@"text"]) {
        // The contents are collected in parser:foundCharacters:.
		self.contentOfCurrentPersonProperty = [NSMutableString stringWithCapacity:30];
	} 
	else {
        self.contentOfCurrentPersonProperty = nil;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{     
    if (qName) {
        elementName = qName;
    }
    
    if ([elementName isEqualToString:@"text"]) {
		if(self.contentOfCurrentPersonProperty==nil || self.contentOfCurrentPersonProperty==@"")
			return;
		else if ([self.currentColumnNumber  isEqualToString:@"2"]) {
			NSString* fullName=self.contentOfCurrentPersonProperty;
			NSRange range=[fullName rangeOfString:@" ,"];
			if(range.location==NSNotFound){
				if([fullName isEqualToString:@""])
					self.currentPersonObject.firstName=@"";
				else
					self.currentPersonObject.firstName=fullName;
				self.currentPersonObject.lastName=@"";
				return;
			}				
			self.currentPersonObject.lastName=[fullName substringToIndex:range.location];
			self.currentPersonObject.firstName=[fullName substringFromIndex:range.location+3];
		}
		else if ([self.currentColumnNumber  isEqualToString:@"3"]) {
			NSString* workContact=self.contentOfCurrentPersonProperty;
			if([workContact hasPrefix:@"Office phone:"]){
				self.currentPersonObject.workPhone=[workContact substringFromIndex:13];
			}
			else if([workContact hasPrefix:@"Office fax:"]){
				self.currentPersonObject.workFax=[workContact substringFromIndex:11];
			}
			else if([workContact hasPrefix:@"Cell phone:"]){
				self.currentPersonObject.mobile=[workContact substringFromIndex:11];
			}
			else if([workContact hasPrefix:@"Pager:"]){
				self.currentPersonObject.workPager=[workContact substringFromIndex:6];
			}
			else if([workContact hasPrefix:@"Home phone:"]){
				return;
			}
			else if([workContact hasPrefix:@"Home fax:"]){
				self.currentPersonObject.homeFax=[workContact substringFromIndex:9];
			}
			else
				return;
		}
		else if ([self.currentColumnNumber  isEqualToString:@"4"]) {
			static BOOL isCompany=YES;
			if(isCompany){
				self.currentPersonObject.company=self.contentOfCurrentPersonProperty;
				isCompany=NO;
			}
			else{
				self.currentPersonObject.jobTitle=self.contentOfCurrentPersonProperty;
				isCompany=YES;
			}		
		}
		else{
			return;
		}
	}
	else if([elementName isEqualToString:@"viewentry"]){
		if(self.currentPersonObject==nil){
			return;
		}
		// Add the new Contact object 
		[self.contacts addObject:self.currentPersonObject];
		return;
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (self.contentOfCurrentPersonProperty) {
		//self.contentOfCurrentMailProperty=string;
        // If the current element is one whose content we care about, append 'string'
        // to the property that holds the content of the current element.
        [self.contentOfCurrentPersonProperty appendString:string];
    }
}

@end
